# -*- coding: UTF-8 -*-
import urllib.request
import pandas as pd
import time,datetime,re
pd.set_option('display.expand_frame_repr', False)

from colorama import init, Fore, Back, Style
init(autoreset=True)

from loguru import logger

currentDate = time.strftime("%Y%m%d", time.localtime())
def get_data(ts_code,scale,datalen,encoding="gbk",):

    url = "http://qt.gtimg.cn/q="+ts_code
    # print(url)
    page = urllib.request.urlopen(url)
    html = page.read()
    html = html.decode(encoding)
    # print("原始字符","="*50)
    '''
    
    '''
    # print(html)
    strlist = html[11:]
    strlist = strlist[:-2]
    stock_list_tmp = list(strlist.split("~"))
    stock=[]
    stock.append(stock_list_tmp[1])
    stock.append(ts_code)
    stock.append(stock_list_tmp[30][0:8])
    stock.append(stock_list_tmp[30][-6:])
    stock.append(stock_list_tmp[5]) #今开
    stock.append(stock_list_tmp[33]) #H
    stock.append(stock_list_tmp[34]) #l
    stock.append(stock_list_tmp[3]) #c
    stock.append(stock_list_tmp[36])#v
    stock.append(stock_list_tmp[37])#a
    # print(stock_list[1])
    # xxxx=list(html[11:])
    # print(xxxx)
    # tmpHtml = html[html.index("var=(") + len("var=("):]
    # final_html = tmpHtml[:len(tmpHtml) - 2]
    # stock_list = eval(stock_list)
    # print("原始字符",type(final_html))
    # print(final_html)
    titleName =["name","ts_code","trade_date", 'trade_time',"open","high","low","close","volume","amount"]
    # titleName = ['trade_date', 'trade_time', 'open', 'high', 'low', 'close', 'volume', 'amount']
    df = pd.DataFrame([stock],columns=titleName)
    df.columns = df.columns.str.upper()
    # print(df)
    return df

def exe():
    logger.info("exec()...")
    df = pd.read_csv("code_list.csv")
    code_lis = df["ts_code"].values.tolist()
    # print(len(code_lis),code_lis)
    i=0

    scale=len(code_lis)
    logger.success("data count :"+str(scale))
    LL=30
    for __list in code_lis:
        codetmpe=__list[0:6]
        mk=__list[-2:]
        tscode=str(mk+codetmpe).lower()
        starttime = datetime.datetime.now()

        df= get_data(tscode, "", "")

        endtime = datetime.datetime.now()

        if i==0:
            dftmp=df
        else:
            df = pd.concat([df,dftmp])
            dftmp =df

        color_para=Fore.RED

        a = (i / scale) * 100
        b = '.' * LL
        c = '▋' * (int((i * LL) / scale))
        b = '.' * ((LL - 1) - int((i * LL) / scale))
        dur = time.perf_counter()  # //每次获取当前时间

        outmessage="get time：" + str(endtime - starttime)
        print(Style.BRIGHT + color_para + "\r[{}]\t{:^3.0f}% {}{} {:.2f}s".format(i, a, c, b, dur), tscode,Fore.GREEN + outmessage, end=' ')


        i+=1
        # if i==100:
        #     break
    logger.success(df.shape[0])
    print(df)
    df.to_csv("163_stock_stock_"+currentDate+".csv")
if __name__ == '__main__':
    logger.info('show_title')
    # os.system("cls")
    starttime = datetime.datetime.now()
    logger.debug("exe。。。")
    exe()
    endtime = datetime.datetime.now()
    logger.success('程序运行时间:' + str(endtime - starttime))
'''
 0: 未知
 1: 名字
 2: 代码
 3: 当前价格
 4: 昨收
 5: 今开
 6: 成交量（手）
 7: 外盘
 8: 内盘
 9: 买一
10: 买一量（手）
11-18: 买二 买五
19: 卖一
20: 卖一量
21-28: 卖二 卖五
29: 最近逐笔成交
30: 时间
31: 涨跌
32: 涨跌%
33: 最高
34: 最低
35: 价格/成交量（手）/成交额
36: 成交量（手）
37: 成交额（万）
38: 换手率
39: 市盈率
40: 
41: 最高
42: 最低
43: 振幅
44: 流通市值
45: 总市值
46: 市净率
47: 涨停价
48: 跌停价
'''